<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区 -->
      <el-table :data="rolesList"
                border
                stripe="">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, index1) in scope.row.children"
                    :key="item1.id"
                    :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable
                        @close="removeRightsById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过v-for渲染二级菜单 -->
                <el-row v-for="(item2, index2) in item1.children"
                        :key="item2.id"
                        :class="[index2 === 0 ? 'margin_bottom' : 'bdtop', 'vcenter']">
                  <el-col :span="6">
                    <el-tag type="success"
                            closable
                            @close="removeRightsById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children"
                            :key="item3.id"
                            type="warning"
                            class="margin_right"
                            closable
                            @close="removeRightsById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"
                         label="序号"
                         width="50px"></el-table-column>
        <el-table-column label="角色名称"
                         prop="roleName"></el-table-column>
        <el-table-column label="角色描述"
                         prop="roleDesc"></el-table-column>
        <el-table-column label="操作"
                         width="300px">
          <template slot-scope="scope">
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini">编辑</el-button>
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini">删除</el-button>
            <el-button type="warning"
                       icon="el-icon-setting"
                       size="mini"
                       @click="showRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限修改对话框 -->
    <el-dialog title="分配权限"
               :visible.sync="setRightdialogVisible"
               width="50%"
               @close="setRightDialogClosed()">
      <!-- 树形控件 -->
      <el-tree :data="rightsList"
               :props="treeProps"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-checked-keys="defKeys"
               ref="treeRef"></el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [], // 所有角色列表数据
      setRightdialogVisible: false, //控制分配权限对话框显示/隐藏
      rightsList: [], // 用户所有权限列表
      treeProps: {
        //树形控件绑定对象
        label: "authName",
        children: "children"
      },
      //默认选中的节点id数组
      defKeys: [105, 116],
      roleId: "" // 当前即将分配权限的id
    };
  },
  methods: {
    //获取所有角色列表
    async getRolesList () {
      const { data: res } = await this.$ajax.get("/roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
    },
    //根据角色id删除对应权限
    removeRightsById (role, rightId) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$ajax
            .delete(`/roles/${role.id}/rights/${rightId}`)
            .then(res => {
              if (res.data.meta.status !== 200) {
                return this.$message.error("删除权限失败");
              }
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              // 由于发送删除请求后返回的是最新的权限数据，所以对role.children重新赋值即可
              role.children = res.data.data;
            })
            .catch(err => {
              console.log("错误信息" + err);
              this.$message.error("删除权限失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async showRightDialog (role) {
      this.roleId = role.id; //将当前id保存到roleId中方便后续使用
      // 获取所以权限数据
      const { data: res } = await this.$ajax.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限列表失败");
      }
      this.rightsList = res.data;

      // 递归拿到三级权限的id
      this.getLeaKeys(role, this.defKeys);

      this.setRightdialogVisible = true;
    },
    // 通过递归得方式拿到所有三级权限的id，并且赋值到defKeys数组中
    getLeaKeys (node, arr) {
      // 如果当前节点不包含childern属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach(item => {
        this.getLeaKeys(item, arr);
      });
    },
    // 当分配权限的对话框关闭的时候调用
    setRightDialogClosed () {
      this.defKeys = [];
    },
    // 当点击分配权限修改对话框中点击确定的时候调用
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");

      const { data: res } = await this.$ajax.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }

      this.$message.success("分配权限成功");
      this.getRolesList();
      this.setRightdialogVisible = false;
    }
  },
  created () {
    this.getRolesList();
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin-top: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
  padding-bottom: 5px;
}

.margin_bottom {
  margin-bottom: 5px;
}

.margin_right {
  margin-right: 10px;
}

.vcenter {
  display: flex;
  align-items: center;
}

.bdbottom {
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}
</style>
